package com.zhengbing.tj.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 统一处理应用程序中抛出的异常，包括自定义异常和运行时异常
 *
 * @author zhengbing
 * @date 2025-07-07
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 显式声明log变量以确保编译通过
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 处理自定义TjException
     */
    @ExceptionHandler(TjException.class)
    public ApiResult<?> handleTjException(TjException ex) {
        log.error("捕获TjException: code={}, message={}, 异常=", ex.getCode(), ex.getMessage(), ex);
        return ApiResult.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理所有运行时异常，统一抛出TjException
     */
    @ExceptionHandler(RuntimeException.class)
    public ApiResult<?> handleRuntimeException(RuntimeException ex) {
        log.error("捕获运行时异常", ex);
        throw new TjException(500, "系统内部错误，请联系管理员");
    }
}